package com.xyq.system.manager;

import cn.hutool.core.bean.BeanUtil;
import com.xyq.common.core.constants.CacheConstants;
import com.xyq.common.core.enums.ResultCode;
import com.xyq.common.core.exception.ServiceException;
import com.xyq.common.redis.service.RedisService;

import com.xyq.system.domain.user.User;
import com.xyq.system.domain.user.vo.UserVO;
import com.xyq.system.mapper.user.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class UserCacheManager {
    @Autowired
    private RedisService redisService;

    @Autowired
    private UserMapper userMapper ;

    public UserVO getUserById(Long userId) {
       String userKey = getUserKey(userId) ;
       // 从redis里查询这个用户的详细信息
       UserVO userVO = redisService.getCacheObject(userKey , UserVO.class) ;
       if(userVO != null){
           // 设置用户缓存有效时间 为 20分钟
           redisService.expire(userKey , CacheConstants.USER_DETAIL_TIME , TimeUnit.MINUTES);
           return userVO ;
       }
        userVO = new UserVO() ;
        // 如果没有去数据库里查
        User user = userMapper.selectById(userId);
        if(user == null){
            throw new ServiceException(ResultCode.FAILED_USER_NOT_EXISTS) ;
        }
        // 密码不存, status不存
         user.setPassword(null);
         // 刷新缓存
         refreshUser(user);
         BeanUtil.copyProperties(user , userVO);
        return userVO ;
    }

    private String getUserKey(Long userId){
        return CacheConstants.USER_DETAIL + userId ;
    }

    // 刷新缓存
    public void refreshUser(User user){
         String userKey = getUserKey(user.getUserId());
         redisService.setCacheObject(userKey , user);
         // 设置用户缓存有效时间 为 20分钟
        redisService.expire(userKey , CacheConstants.USER_DETAIL_TIME , TimeUnit.MINUTES);
    }

}
